package com.zzw.junit5demo.extension;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.LifecycleMethodExecutionExceptionHandler;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * @author zzw
 * @version 1.0
 * @title IgnoreExceptionExtension
 * @description <description class purpose>
 * @datetime 2023-06-16 22:01
 */
public class IgnoreExceptionExtension implements TestExecutionExceptionHandler, LifecycleMethodExecutionExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(IgnoreExceptionExtension.class);

    @Override
    public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {

        if (throwable instanceof IOException) {
            logger.error("【{}】 发生了IO异常", context.getDisplayName());
            return;
        }

        if (throwable instanceof RuntimeException) {
            logger.error("【{}】 发生了运行时异常 => {}", context.getDisplayName(),
                    throwable.getMessage());
            return;
        }

        throw throwable;
    }


    @Override
    public void handleBeforeAllMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
        throw throwable;
    }

    @Override
    public void handleBeforeEachMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
        throw throwable;
    }

    @Override
    public void handleAfterEachMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
        if (throwable instanceof NullPointerException) {
            logger.error("【AfterEach】 发生了NPE异常 => {}", throwable.getMessage());
            return;
        }

        throw throwable;
    }

    @Override
    public void handleAfterAllMethodExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
        throw throwable;
    }
}
